import React, { useEffect, useState, useRef } from 'react';
import { Button, Tag, Space, Image, Avatar, message } from 'antd';
import ProList from '@ant-design/pro-list';
import request from 'umi-request';
import { Link } from 'umi';
import { PageContainer } from '@ant-design/pro-layout';
import InsertComponent from './components/InsertComponent';
import { ModalForm } from '@ant-design/pro-form';
import dayjs from 'dayjs';
import UpdateComponent from './components/UpdateComponent';
import ProCard from '@ant-design/pro-card';
import { api } from '@/global';
type CourseType = {
  id: number;
  courseName: string;
  courseCode: number;
  professionalName: string;
  teachName: string;
  classesName: string;
  courseStatu: number;
  courseAvatar: string;
  courseGrade: number;
};

const getWindowSize: any = () => ({
  innerHeight: window.innerHeight,
  innerWidth: window.innerWidth,
});

export default () => {
  const [windowSize, setWindowSize] = useState(getWindowSize());
  const actionRef = useRef<ActionType>();

  const handleResize = () => {
    setWindowSize(getWindowSize());
  };

  useEffect(() => {
    window.addEventListener('resize', handleResize);
  }, []);

  function reloadPage() {
    actionRef.current?.reload();
  }

  return (
    <PageContainer
      waterMarkProps={{
        content: '山西工程技术学院',
      }}
      header={{
        title: '课程管理',
        breadcrumb: {
          routes: [
            {
              path: '',
              breadcrumbName: '组织管理',
            },
            {
              path: '',
              breadcrumbName: '课程管理',
            },
          ],
        },
      }}
    >
      <ProList<CourseType>
        toolBarRender={() => {
          return [<InsertComponent key="3" reloadPage={reloadPage} />];
        }}
        actionRef={actionRef}
        search={{}}
        rowKey="name"
        headerTitle="课程列表"
        request={async (params = {}) => {
          const result = await request<{
            data: CourseType[];
          }>(api.getCourseList, {
            method: 'POST',
            data: {
              ...params,
            },
          });

          return result;
        }}
        pagination={{
          pageSize: 20,
        }}
        grid={{
          gutter: windowSize.innerWidth < 535 ? 32 : windowSize.innerWidth < 920 ? 16 : 8,
          column: windowSize.innerWidth < 535 ? 1 : windowSize.innerWidth < 920 ? 2 : 4,
        }}
        showActions="hover"
        metas={{
          title: {
            dataIndex: 'courseName',
            title: '班级名称',
          },
          avatar: {
            dataIndex: 'courseAvatar',
            search: false,
            render: (_, row) => {
              return (
                <Avatar
                  key={row.id}
                  size="small"
                  src="https://gw.alipayobjects.com/zos/antfincdn/UCSiy1j6jx/xingzhuang.svg"
                />
              );
            },
          },
          content: {
            dataIndex: 'courseDesc',
            search: false,
            render: (_, row) => {
              const list = row.classesName.split(',');

              return (
                <div>
                  <Space size={1} split="">
                    <span style={{ color: '#597e82', fontWeight: 400 }} key={row.id}>
                      {row.professionalName}
                    </span>
                  </Space>
                  <br />

                  {list.map((item, index: number, _) => {
                    return (
                      <Tag
                        aria-colspan={{ xs: 24, sm: 12, md: 12, lg: 12, xl: 12 }}
                        color="#12b886"
                        key={index}
                      >
                        {item}
                      </Tag>
                    );
                  })}

                  <br />
                  <Space size={0} style={{ marginTop: '5px' }}>
                    <span key={row.id}>
                      任课教师:{' '}
                      <span style={{ color: 'black', fontWeight: 600 }}>{row.teachName}</span>
                    </span>
                  </Space>
                </div>
              );
            },
          },
          subTitle: {
            dataIndex: 'labels',
            render: (_, row) => {
              let tag;

              if (row.courseStatu === 1) {
                tag = <Tag color="#3498db">正在进行</Tag>;
              } else if (row.courseStatu === 2) {
                tag = <Tag color="#a4b0be">已经节课</Tag>;
              } else {
                tag = <Tag color="#2ecc71">其他</Tag>;
              }

              return (
                <Space key={row.id} size={1}>
                  <Tag color="#3498db">{row.courseGrade}</Tag>
                  {tag}
                </Space>
              );
            },
            search: false,
          },
          actions: {
            cardActionProps: 'actions',
            render: (text, row) => [
              <Link
                key="look"
                to={'/organizational_management/source_manager/source_info?id=' + row.id}
              >
                <a>查看</a>
              </Link>,
              <UpdateComponent key={row.id + '2'} currentId={row.id} reloadPage={reloadPage} />,
              <ModalForm
                key={row.id + '1'}
                title="删除"
                trigger={<a rel="noopener noreferrer">删除</a>}
                autoFocusFirstInput
                onFinish={async (values) => {
                  const result = await request(api.deleteCourse, {
                    method: 'POST',
                    data: {
                      id: row.id,
                    },
                  });

                  if (result.success) {
                    message.success('删除成功');
                    reloadPage();
                  } else {
                    message.success('删除失败');
                  }

                  return true;
                }}
              >
                是否删除&nbsp;&nbsp;
                <span style={{ fontWeight: 900, fontSize: 25, color: '#3498db' }}>
                  {row.courseName}
                </span>
                &nbsp;&nbsp; 课程
              </ModalForm>,
            ],
            search: false,
          },
          status: {
            // 自己扩展的字段，主要用于筛选，不在列表中显示
            title: '状态',
            valueType: 'select',
            request: () => {
              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              list.push({
                label: '正在进行',
                value: 1,
              });
              list.push({
                label: '已经节课',
                value: 2,
              });
              list.push({
                label: '其他',
                value: 3,
              });
              return list;
            },
          },
          Dept: {
            title: '系部',
            dataIndex: 'dept',
            valueType: 'select',
            request: async () => {
              const deptData = await request(api.getAllDept, {});
              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              deptData.data.map((item: deptTyp) => {
                list.push({
                  label: item.deptName,
                  value: item.id,
                });
              });

              return list;
            },
          },
          prfessional: {
            title: '专业',
            dataIndex: 'professional',
            valueType: 'select',
            request: async () => {
              const conditionData = await request(api.getSimpleProfessional, {});

              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              conditionData.data.map((item: professionalType) => {
                list.push({
                  label: item.professionalName,
                  value: item.id,
                });
              });

              return list;
            },
          },
          classes: {
            title: '班级',
            dataIndex: 'classes',
            valueType: 'select',
            request: async () => {
              const conditionData = await request(api.getClassesList, {});

              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              conditionData.data.map((item: professionalType) => {
                list.push({
                  label: item.className,
                  value: item.id,
                });
              });

              return list;
            },
          },
          teacher: {
            title: '任课教师',
            dataIndex: 'teacher',
            valueType: 'select',
            request: async () => {
              const conditionData = await request(api.getTeacherList, {});

              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });
              conditionData.data.map((item: professionalType) => {
                list.push({
                  label: item.name,
                  value: item.id,
                });
              });

              return list;
            },
          },

          grade: {
            title: '年级',
            dataIndex: 'grade',
            valueType: 'select',
            request: async () => {
              const { data } = await request(api.getEarlyYear, {});

              let year = dayjs().year();

              const list: any[] = [];
              list.push({
                label: '全部',
                value: 0,
              });

              while (year - 2000 - data >= 0) {
                list.push({
                  label: String(year - 2000) + '级',
                  value: year - 2000,
                });
                year = year - 1;
              }

              return list;
            },
          },
        }}
      />
    </PageContainer>
  );
};
